<template>
  <div>
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="pb-5 font-bold text-14px">仓库：{{ whsName }}</div>
        </el-col>
        <!--产品分类-->
        <el-col :span="4" :xs="24">
          <el-card class="box-card">
            <template #header>
              <div class="font-bold text-14px">
                <el-icon><List /></el-icon><span> 产品分类</span>
              </div>
            </template>

            <el-tree
              ref="avueTree"
              :data="treeData"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children'
              }"
              highlight-current
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <a class="node-title" @click.self="nodeClick(data)">
                    {{ node.label }}
                  </a>
                </div>
              </template>
            </el-tree>
          </el-card>
        </el-col>
        <!--产品列表-->
        <el-col :span="20" :xs="24">
          <el-card class="box-card">
            <div class="mb6">
              <!-- <span>
                <el-button icon="Plus" type="primary" @click="handleAdd"
                  >增加产品</el-button
                >
                <el-button
                  icon="Edit"
                  :disabled="disUpdate"
                  type="primary"
                  plain
                  @click="handleUpdate"
                  >编辑产品</el-button
                >
                <el-button
                  icon="Delete"
                  :disabled="disDel"
                  type="primary"
                  plain
                  @click="handleDel"
                  >删除产品</el-button
                >
              </span> -->
              <div class="inline-block align-top float-right">
                <el-form
                  :model="queryParams"
                  ref="queryRef"
                  :inline="true"
                  label-width="0"
                  @submit.prevent
                >
                  <el-form-item prop="zeroDisplay">
                    <el-checkbox
                      v-model="queryParams.zeroDisplay"
                      label="零库存显示"
                      size="large"
                      @change="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item prop="keyword">
                    <el-input
                      v-model="queryParams.keyword"
                      placeholder="输入搜索关键词"
                      clearable
                      style="width: 200px"
                      @keyup.enter="handleQuery"
                      @blur="handleQuery"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <el-table
              v-loading="loading"
              :data="dataList"
              row-key="id"
              stripe
              :border="true"
              current-row-key="id"
              @selection-change="handleSelectionChange"
            >
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column prop="name" label="产品名称">
                <template #default="scope">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="
                      goTo('/source/product/details', {
                        productId: scope.row.productId
                      })
                    "
                    >{{ scope.row.name }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column prop="number" label="产品编号" width="150">
              </el-table-column>
              <el-table-column prop="price" label="销售单价" width="150">
              </el-table-column>
              <el-table-column
                prop="specification"
                label="规格型号"
                width="100"
              >
              </el-table-column>
              <el-table-column
                label="库存数"
                align="center"
                prop="inventory"
                width="160"
              >
                <template #default="scope">
                  <span>{{ scope.row.inventory }}</span>
                  <span v-show="scope.row.preOut != 0"
                    >(锁定{{ scope.row.preOut }})</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="更新时间"
                align="center"
                prop="updateTime"
                width="160"
              >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="plateType" label="板块类型" width="150">
                <template #default="scope">
                  <dict-drop
                    :options="ord_product_plate_type"
                    :value="scope.row.plateType"
                /></template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="250"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Checked"
                    @click="handleEnter(scope.row)"
                    >入库</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="Failed"
                    @click="handleGoOut(scope.row)"
                    >出库</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="List"
                    @click="handleHistory(scope.row)"
                    >历史</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              class="mr-4 relative"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 出入库对话框 -->
      <el-dialog
        :title="inventoryDialog.title"
        v-model="inventoryDialog.open"
        :width="inventoryDialog.width"
        append-to-body
        @close="cancel"
      >
        <el-form
          ref="inventoryRef"
          :model="inventoryForm"
          :rules="inventoryRules"
          label-width="140px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称">
                <el-input disabled v-model="rowData.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编号">
                <el-input disabled v-model="rowData.number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格型号">
                <el-input disabled v-model="rowData.specification"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库">
                <el-input disabled v-model="rowData.warehouseName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已入库数量">
                <el-input disabled v-model="rowData.inventory">
                  <template #append>
                    <!-- {{ measurement_unit[rowData.unit].label }} -->
                    {{
                      selectDictLabel(measurement_unit, rowData.unit)
                    }}</template
                  ></el-input
                >
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="采购数量">
                <el-input disabled v-model="rowData.num">
                  <template #append>{{
                    measurement_unit[rowData.unit].label
                  }}</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="采购单价">
                <el-input disabled v-model="rowData.price"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购备注">
                <el-input disabled v-model="rowData.remark"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-model="inventoryForm.supplierId"
                  placeholder="请输入供应商名称选择供应商"
                  class="w-full"
                  suffix-icon="Search"
                  remote-show-suffix
                  :suffix-transition="false"
                  filterable
                  remote
                  @change="val => changeSupplier(val)"
                  :remote-method="val => querySupplier(val)"
                  :loading="loadingSelect"
                  no-data-text="未查询到供应商"
                >
                  <el-option
                    v-for="item in supplierOptions"
                    :key="item.id"
                    :label="item.supplierName"
                    :value="item.id"
                  >
                    <div>
                      <span>{{ item.supplierName }}</span>
                      <span v-if="item.supplierNumber"
                        >({{ item.supplierNumber }})</span
                      >
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="
                  inventoryDialog.title == '入库登记' ? '入库数量' : '出库数量'
                "
                prop="num"
              >
                <el-input
                  placeholder="请输入一个有效数值"
                  v-model="inventoryForm.num"
                  ><template #append>
                    <!-- {{ measurement_unit[rowData.unit].label }} -->
                    {{
                      selectDictLabel(measurement_unit, rowData.unit)
                    }}</template
                  ></el-input
                >
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="入库类型"
                v-if="inventoryDialog.title == '入库登记'"
              >
                <el-select
                  class="w-full"
                  v-model="inventoryForm.inboundType"
                  placeholder="请选择入库类型"
                >
                  <el-option
                    v-for="item in inbound_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="出库类型"
                v-else-if="inventoryDialog.title == '出库登记'"
              >
                <el-select
                  class="w-full"
                  v-model="inventoryForm.outboundType"
                  placeholder="请选择出库类型"
                >
                  <el-option
                    v-for="item in outbound_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="
                  inventoryDialog.title == '入库登记' ? '入库备注' : '出库备注'
                "
              >
                <el-input
                  v-model="inventoryForm.remark"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="登记人：">
                {{ useUserStore().user.nickName }}</el-form-item
              ></el-col
            >
            <el-col :span="12">
              <el-form-item label="登记时间："> {{ time }} </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 库存历史对话框 -->
      <el-dialog
        :title="historyDialog.title"
        v-model="historyDialog.open"
        :width="historyDialog.width"
        append-to-body
        @close="historyDialog.open = false"
      >
        <div>
          <el-table
            v-loading="historyloading"
            :data="historyList"
            row-key="id"
            stripe
            :border="true"
            current-row-key="id"
            :header-cell-class-name="setClass"
          >
            <el-table-column prop="productName" label="产品名称">
              <!-- <template #default="scope">
                <el-link
                  type="primary"
                  :underline="false"
                  @click="
                    goTo('/source/product/details', {
                      productId: scope.row.id
                    })
                  "
                  >{{ scope.row.name }}</el-link
                >
              </template> -->
            </el-table-column>
            <el-table-column
              prop="productNumber"
              label="产品编号"
              width="150"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="specification"
              label="规格型号"
              width="100"
              align="center"
            >
            </el-table-column>
            <!-- ord_order 销售订单  ord_purchase_order 采购订单 ord_inner_order 内部订单 -->
            <el-table-column
              label="所属订单"
              align="center"
              prop="orderTitle"
              width="160"
            >
              <template #default="scope">
                <div>
                  <el-link
                    type="primary"
                    :underline="false"
                    v-if="scope.row.orderType == 'ord_order'"
                    @click="
                      () => {
                        goTo('/sales/indent/salesOrderDetails', {
                          salesOrderId: scope.row.orderId
                        })
                        historyDialog.open = false
                      }
                    "
                    >查看订单</el-link
                  >
                  <el-link
                    type="primary"
                    :underline="false"
                    v-else-if="scope.row.orderType == 'ord_purchase_order'"
                    @click="
                      () => {
                        goTo('/source/purchaseOrder/purchaseOrderA8Form', {
                          purchaseOrderId: scope.row.orderId
                        })
                        historyDialog.open = false
                      }
                    "
                    >查看订单</el-link
                  >
                  <el-link
                    type="primary"
                    :underline="false"
                    v-else-if="scope.row.orderType == 'ord_inner_order'"
                    @click="
                      () => {
                        goTo('/source/innerOrder/innerOrderA8Form', {
                          innerOrderId: scope.row.orderId
                        })
                        historyDialog.open = false
                      }
                    "
                    >查看订单</el-link
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="登记人"
              align="center"
              prop="createName"
              width="90"
            >
            </el-table-column>
            <el-table-column
              label="登记时间"
              align="center"
              prop="createTime"
              width="160"
            >
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="inboundType"
              label="类型"
              width="90"
              align="center"
            >
              <template #default="scope">
                <dict-drop
                  v-if="scope.row.inOutType == '2'"
                  :options="inbound_type"
                  :value="scope.row.inboundType" />
                <dict-drop
                  v-if="scope.row.inOutType == '1'"
                  :options="outbound_type"
                  :value="scope.row.outboundType"
              /></template>
            </el-table-column>
            <el-table-column
              prop="inOutType"
              label="出入库"
              width="70"
              align="center"
            >
              <template #default="scope">
                <dict-drop :options="in_out_type" :value="scope.row.inOutType"
              /></template>
            </el-table-column>
            <el-table-column
              prop="num"
              label="变动数量"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="supplierName" label="供应商" width="150">
            </el-table-column>
          </el-table>

          <pagination
            v-show="historyTotal > 9"
            :total="historyTotal"
            class="mr-4 relative"
            v-model:page="historyParams.pageNum"
            v-model:limit="historyParams.pageSize"
            @pagination="getHistoryList"
          />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="historyDialog.open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="InventoryList">
import { reactive, toRefs, ref } from 'vue'
import { listCategory } from '@/api/productMange/product'
import {
  measurement_unit, //产品单位
  loadingSelect, //远程检索loading
  supplierOptions, //供应商数据
  querySupplier //检索供应商
} from '@/hooks/dict/order'
import {
  listInventory,
  setInbound,
  setOutbound,
  listwhsHistory
} from '@/api/warehouseManage/warehouse'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { maxDecimals } from '@/utils/validate'
const props = defineProps({
  productData: {
    type: Object,
    require: false,
    default: () => {
      return {}
    }
  },
  productQuery: {
    type: Object,
    require: false,
    default: () => {}
  }
})
const emit = defineEmits(['selectionChange'])
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const { ord_product_plate_type, inbound_type, outbound_type, in_out_type } =
  proxy.useDict(
    'ord_product_plate_type',
    'inbound_type',
    'outbound_type',
    'in_out_type'
  )
const treeData = ref([
  {
    value: 100,
    label: '一级部门',
    children: [
      {
        value: 1,
        label: '一级部门1'
      },
      {
        value: 2,
        label: '一级部门2'
      }
    ]
  },
  {
    value: 3,
    label: '二级部门',
    children: [
      {
        value: 4,
        label: '二级部门1'
      },
      {
        value: 5,
        label: '二级部门2'
      }
    ]
  }
])
const data = reactive({
  loading: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    zeroDisplay: false,
    categoryId: undefined, //产品分类
    keyword: undefined //关键词
  },
  dataList: [],
  ids: [],
  selectArr: [],
  total: 0,
  disUpdate: true,
  disDel: true,
  whsName: '',

  inventoryDialog: {
    title: '新增',
    open: false,
    width: '800px'
  },
  inventoryForm: {
    num: null,
    supplierId: null,
    remark: null,
    type: '2'
  },
  inventoryRules: {
    num: [
      { message: '请输入数量', required: true, trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          maxDecimals(rule, value, callback, 6)
        }
      }
    ],
    supplierId: [{ message: '请输入供应商', required: false, trigger: 'blur' }]
  },
  rowData: {},
  time: proxy.parseTime(new Date(new Date().getTime())),
  historyDialog: {
    title: '出入库历史',
    open: false,
    width: '1200px'
  },
  historyloading: false,
  historyList: [],
  historyTotal: 0,
  historyParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined, //产品分类
    productId: undefined //关键词
  }
})

let {
  loading,
  ids,
  selectArr,
  total,
  queryParams,
  dataList,
  disUpdate,
  disDel,
  whsName,
  inventoryDialog,
  inventoryForm,
  inventoryRules,
  rowData,
  time,
  historyDialog,
  historyloading,
  historyList,
  historyTotal,
  historyParams
} = toRefs(data)
watch(
  [() => route.query.warehouseId, () => route.query.warehouseName],
  () => {
    whsName.value = route.query.warehouseName
    queryParams.value.warehouseId = route.query.warehouseId
  },
  {
    immediate: true
  }
)

function goTo(url, data) {
  router.push({ path: url, query: data })
}
function init() {
  // queryParams.value = { ...queryParams.value, ...props.productQuery }
  getList()
  getTreeList()
}
/** 搜索按钮操作 */
function handleQuery() {
  //   console.log('检索')
  getList()
}
// 获取数据列表
function getList() {
  loading.value = true

  listInventory(queryParams.value).then(res => {
    loading.value = false
    dataList.value = res.rows
    total.value = res.total
    console.log(' dataList.value==>', dataList.value)
  })
}
// 获取数据列表
function getTreeList() {
  listCategory().then(res => {
    treeData.value = res.data //proxy.handleTree(res.data)
    // console.log(' treeData.value==>', treeData.value)
  })
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDel.value = !selection.length
  emit('selectionChange', selectArr.value)
}

// 树节点点击
function nodeClick(data) {
  queryParams.value.categoryId = data.id
  getList()
  //   proxy.$message.success(JSON.stringify(data))
}
// 确认新增修改
function submitForm() {
  proxy.$refs.inventoryRef.validate(valid => {
    if (valid) {
      if (inventoryDialog.value.title == '入库登记') {
        setInbound(inventoryForm.value).then(() => {
          proxy.$modal.msgSuccess('入库成功')
          inventoryDialog.value.open = false
          getList()
        })
      } else if (inventoryDialog.value.title == '出库登记') {
        setOutbound(inventoryForm.value).then(() => {
          proxy.$modal.msgSuccess('出库成功')
          inventoryDialog.value.open = false
          getList()
        })
      }
    }
  })
}
// 选择供应商时的方法
function changeSupplier(val) {
  let supplier = supplierOptions.value.filter(item => {
    return item.id == val
  })
  inventoryForm.value.supplierName = supplier[0].supplierName
}
//重置
function cancel() {
  inventoryDialog.value.open = false
  reset()
}

/** 表单重置 */
function reset() {
  inventoryForm.value = {}
  proxy.resetForm('inventoryRef')
}

// 入库按钮
function handleEnter(row) {
  rowData.value = row
  let { productId, warehouseId } = row
  inventoryDialog.value.title = '入库登记'
  inventoryDialog.value.open = true
  inventoryForm.value.productId = productId
  inventoryForm.value.warehouseId = warehouseId
}
// 出库按钮
function handleGoOut(row) {
  rowData.value = row
  let { productId, warehouseId } = row
  inventoryDialog.value.title = '出库登记'
  inventoryDialog.value.open = true
  inventoryForm.value.productId = productId
  inventoryForm.value.warehouseId = warehouseId
}

// 历史按钮
function handleHistory(row) {
  historyList.value = []
  let { productId, warehouseId } = row
  historyDialog.value.title = '出入库历史'
  historyDialog.value.open = true
  historyParams.value.productId = productId
  historyParams.value.warehouseId = warehouseId
  getHistoryList()
}
// 获取历史列表
function getHistoryList() {
  historyloading.value = true

  listwhsHistory(historyParams.value).then(res => {
    historyloading.value = false
    historyList.value = res.rows
    historyTotal.value = res.total
    console.log(' historyList.value==>', historyList.value)
  })
}

// 设置表头内容居中

function setClass({ row, rowIndex }) {
  if (rowIndex === 0) {
    return 'textCenter'
  }
}
init()
</script>
<style scoped>
.box-card {
  min-height: 85vh;
}
.custom-tree-node {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.custom-tree-node .node-title {
  flex-grow: 8;
}
.custom-tree-node .node-btn {
  display: none;
  flex-grow: 1;
}
.el-tree-node__content:hover .node-btn {
  display: block;
}
.avatar-uploader:deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:deep(.el-upload:hover) {
  border-color: #409eff;
}
.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: #8c939d;
  width: 178px;
  height: 178px;
}
.avatar-uploader-icon i {
  font-size: 30px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.textCenter) {
  text-align: center;
}
</style>
